/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 096.c
 * Sort
 ***********************************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#define NUM 7

int score[NUM] = {5, 3, 4, 7, 3, 5, 6};
int id[NUM] = {1, 2, 3, 4, 5, 6, 7};
int rank[NUM];

/*
 * this program uses qsort function of standard library to sort
 * and assume that highest score leads to first rank, which is different to the book
 */

int cmp(const void* a, const void* b)
{
    int *aa = (int*)a, *bb = (int*)b;
    int x = score[*aa-1], y = score[*bb-1];
    if (x > y) return(-1);
    else if (x < y) return(1);
    else return (0);
}

void print(int* array)
{
    int i;
    for (i = 0; i < NUM; i++)
        printf("%d ", array[i]);
    printf("\n");
}

int main()
{
    int i, j;
    printf("ID:\n");
    print(id);
    printf("SCORE:\n");
    print(score);
    qsort(id, NUM, sizeof(int), cmp);
    printf("RANKED ID:\n");
    print(id);
    j = 1;
    for (i = 0; i < NUM; i++)
    {
        // same score with different rank
        /*
        rank[id[i]-1] = j;
        j++;
        */
        // same score with same rank, continuous rank
        /*
        rank[id[i]-1] = j;
        if (i+1 == NUM) continue;
        while (score[id[i]-1] == score[id[i+1]-1])
        {
            rank[id[i+1]-1] = j;
            i++;
        }
        j++;
        */
        // same score with same rank, in-continuous rank
        int k = 1;
        rank[id[i]-1] = j;
        if (i+1 == NUM) continue;
        while (score[id[i]-1] == score[id[i+1]-1])
        {
            rank[id[i+1]-1] = j;
            i++;
            k++;
        }
        j += k;
    }
    printf("RANK:\n");
    print(rank);
}

